# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "泰然无忧百万医疗保险"
    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,61)],
                #有无社保
                "socialSec":["Y"],
                #一般医疗保险金
                "generalMedical":["3000000"],
                #恶性肿瘤保险金
                "cancerMedical":["3000000"],
                #免赔额
                "deductible":["1"],
                #保障期限
                "expire":["1年"],
                #交费类型
                "payType":["年交"],
                #产品计划
                "plan":["A"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["N"],
                # 一般医疗保险金
                "generalMedical": ["3000000"],
                # 恶性肿瘤保险金
                "cancerMedical": ["3000000"],
                # 免赔额
                "deductible": ["1"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 产品计划
                "plan": ["B"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y"],
                # 一般医疗保险金
                "generalMedical": ["3000000"],
                # 恶性肿瘤保险金
                "cancerMedical": ["3000000"],
                # 免赔额
                "deductible": ["0"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 产品计划
                "plan": ["C"]
            },
        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["socialSec"],plan[k]["generalMedical"],plan[k]["cancerMedical"],plan[k]["deductible"],plan[k]["expire"],plan[k]["payType"],plan[k]["plan"]):
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]
                ))
                self.mysql._conn.commit()
                print(
                    domain[self.name]["insert_sql"].format(
                        v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]
                    )
                )
    #执行爬虫
    def requestJson(self,dt=None):

        if dt["plan"] == "A":
            pack = "B848"
        elif dt["plan"] == "B":
            pack = "B849"
        else:
            pack = "B846"
        data = {
            "pid": "43",
            "skuCode": pack,
            "device": "pc",
            "age": dt["year"],
            "birthday": "{0} - 01 - 01".format( str(2020-int(dt["year"]))),
            "c_durTime_start": "2020 - 03 - 13",
            "durTime": "365"
        }

        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and not r.json()["error"]:
            price = Helper.decimalParse( r.json()["messages"]["data"]["price"] )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data= {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品信息更新失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
